package;

import utils.SaveData;
import haxe.ui.layouts.VerticalLayout;
import haxe.ui.layouts.HorizontalLayout;
import electron.remote.IpcMain;
import editer.EditFileView;
import haxe.io.Path;
import js.html.IFrameElement;
import data.ZProjuectData.ZProjectData;
import data.AppData;
import utils.Theme;
import haxe.ui.events.UIEvent;
import haxe.ui.notifications.NotificationType;
import haxe.ui.notifications.NotificationManager;
import views.CheckFileView;
import views.ToolsView;
import electron.renderer.IpcRenderer;
import haxe.ui.containers.Splitter;
import haxe.ui.containers.VBox;
import haxe.ui.events.MouseEvent;
import electron.FileSystem;
import utils.FileSystem;
import sys.io.File;

@:build(haxe.ui.ComponentBuilder.build("assets/main-view.xml"))
class MainView extends VBox {
	public static var current:MainView;

	public var projectPath = '';

	public var filterFileName = '';

	public var tabKey = '';

	public var files = [];

	public var tabs = [];

	public function new() {
		super();
		current = this;
	}

	private var __init:Bool = false;

	override function onInitialize() {
		super.onInitialize();
		__init = true;
		trace(this.actualComponentWidth, this.actualComponentHeight);
		// this.left_box.percentWidth = 260 / this.actualComponentWidth * 100;
		// this.splitter_right.percentWidth = 100 - this.left_box.percentWidth;
		// this.content_box.percentWidth = 260 / (this.actualComponentWidth - 260) * 100;
		// this.right_box.percentWidth = 100 - this.content_box.percentWidth;
		this.listenerSplitter(splitter_left);
		this.listenerSplitter(splitter_right);

		// this.spine_version.selectedIndex = SaveData.getItem("spine_version", 0);
		// this.iframe.url = this.getSpineRunTimePath();
		this.dark_theme.selected = SaveData.getItem("theme", "dark") == "dark";

		IpcRenderer.on("build", () -> {
			this.perview(cast this.editer.tabview.selectedPage);
		});
		IpcRenderer.on("f5", () -> {
			// 刷新项目
			updateProjectData();
		});
		IpcRenderer.on("save", () -> {
			this.onSave(null);
		});
	}

	/**
	 * 更新项目数据，如资源列表、预览地址等
	 */
	private function updateProjectData():Void {
		if (AppData.currentProject != null) {
			AppData.currentProject.updateFiles();
			this.assets_manager.setProjectData(AppData.currentProject);
			// 刷新预览网页
			var src = iframe.getIFrame().src;
			iframe.getIFrame().src = src;
			iframe.getIFrame().onload = function() {
				// 刷新项目
				untyped iframe.getIFrame().contentWindow.window.updateSize(AppData.currentProject.HDWidth, AppData.currentProject.HDHeight);
				// 打开预览
				this.perview(cast this.editer.tabview.selectedPage);
			};
		}
	}

	/**
	 * 侦听切割器处理，触摸时，则会屏蔽主要iframe的内容，避免无法操作
	 * @param splitter 
	 */
	public function listenerSplitter(splitter:Splitter):Void {
		splitter.element.addEventListener("mousedown", function(e:MouseEvent) {
			if (editer.tabview.selectedPage != null)
				editer.tabview.selectedPage.element.style.pointerEvents = "none";
			iframe.element.style.pointerEvents = "none";
		});
		splitter.element.addEventListener("mouseup", function(e:MouseEvent) {
			if (editer.tabview.selectedPage != null)
				editer.tabview.selectedPage.element.style.pointerEvents = "auto";
			iframe.element.style.pointerEvents = "auto";
		});
	}

	@:bind(is_hengxiang, UIEvent.CHANGE)
	public function onOrientationChange(e:UIEvent):Void {
		if (is_hengxiang.selected) {
			frame_box.width = 650;
			frame_box.height = 300;
		} else {
			frame_box.width = 300;
			frame_box.height = 650;
		}
	}

	@:bind(btn_save, MouseEvent.CLICK)
	public function onSave(e:MouseEvent):Void {
		var page:EditFileView = cast this.editer.tabview.selectedPage;
		if (page != null) {
			var code = untyped page.frame.getIFrame().contentWindow.window.getCodeValue();
			var path = page.url;
			if (code != null && path != null) {
				File.saveContent(path, code);
				// page.is = false;
				NotificationManager.instance.addNotification({
					title: "保存文件成功",
					body: path + "已保存",
					type: NotificationType.Success
				});
			}
		}
	}

	/**
	 * 打开已存在的项目
	 * @param e 
	 */
	@:bind(btn_open, MouseEvent.CLICK)
	public function onOpen(e:MouseEvent):Void {
		// 打开项目逻辑
		FileSystem.openFile({
			title: "选择project.xml文件",
			filters: [
				{
					name: "项目配置文件",
					extensions: ["xml"]
				}
			]
		}, (data) -> {
			if (!data.canceled) {
				AppData.currentProject = new ZProjectData(data.filePaths[0]);
				this.assets_manager.setProjectData(AppData.currentProject);
				this.projectPath = data.filePaths[0];
				this.is_hengxiang.selected = AppData.currentProject.isLandsapce();
				untyped iframe.getIFrame().contentWindow.window.updateSize(AppData.currentProject.HDWidth, AppData.currentProject.HDHeight);
			}
		});
	}

	// public function onFilterChange():Void {
	// 	if (AppData.currentProject == null) {
	// 		return;
	// 	}
	// 	var list:Array<{label:String, path:String}> = [];
	// 	var checkName:String = filterFileName ?? "";
	// 	checkName = checkName.toLowerCase();
	// 	for (key => value in AppData.currentProject.builderFiles) {
	// 		if (value.name.toLowerCase().indexOf(checkName) != -1)
	// 			list.push({
	// 				label: value.name,
	// 				path: value.path
	// 			});
	// 	}
	// 	this.files = list;
	// }

	@:bind(btn_new, MouseEvent.CLICK)
	public function onAddNewFile(e:MouseEvent):Void {
		// 新建文件
		FileSystem.saveFile(null, (data) -> {
			if (!data.canceled) {
				if (!sys.FileSystem.exists(data.filePath)) {
					trace("保存成功：", data.filePath);
					File.saveContent(data.filePath, '<Scene></Scene>');
					// 从标签打开对应的文件
					var path = new Path(data.filePath);
					this.addTap({
						title: path.file,
						path: data.filePath,
						name: path.file,
						lock: true,
						isChange: false,
						code: File.getContent(data.filePath)
					});
					this.onTabChange({
						props: {
							name: path.file
						}
					});
				} else {
					NotificationManager.instance.addNotification({
						title: "新建文件失败！",
						body: "文件：" + data.filePath + "已经存在，请删除后操作",
						type: NotificationType.Error
					});
				}
				this.updateProjectData();
			}
		});
	}

	public function addTap(item:TapData):Void {
		var array:Array<TapData> = this.tabs;
		if (array.filter((a) -> a.name == item.name).length == 0)
			array.push(item);
		this.tabs = array;
	}

	public function onTabChange(item):Void {
		if (this.tabKey != item.props.name) {
			this.tabKey = item.props.name;
			// 渲染到编辑器中
		}
	}

	/**
	 * 调试界面
	 * @param e 
	 */
	@:bind(btn_debug, MouseEvent.CLICK)
	public function onOpenConsole(e:MouseEvent):Void {
		this.perview(cast this.editer.tabview.selectedPage);
	}

	/**
	 * PSD导出界面
	 * @param e 
	 */
	@:bind(btn_psd, MouseEvent.CLICK)
	public function onOpenDebug(e:MouseEvent):Void {
		var window = new ToolsView();
		window.showDialog();
	}

	/**
	 * 查看文件资源界面
	 * @param e 
	 */
	@:bind(btn_checkFile, MouseEvent.CLICK)
	public function onOpenCheckFile(e:MouseEvent):Void {
		var window = new CheckFileView();
		window.showDialog();
	}

	/**
	 * 更新版本
	 * @param e 
	 */
	@:bind(btn_update, MouseEvent.CLICK)
	public function onOpenUpdate(e:MouseEvent):Void {
		// NotificationManager.instance.addNotification({
		//     title: "更新版本成功！",
		//     body: "你的版本已经更新到最新版本",
		//     type: NotificationType.Success
		// });
		NotificationManager.instance.addNotification({
			title: "更新版本失败！",
			body: "更新程序包发生了错误",
			type: NotificationType.Error
		});
	}

	/**
	 * 暗黑模式切换
	 * @param e 
	 */
	@:bind(dark_theme, UIEvent.CHANGE)
	public function onDarkChange(e:UIEvent):Void {
		if (!__init)
			return;
		var theme = dark_theme.selected ? "dark" : "light";
		SaveData.setItem("theme", "dark");
		Theme.setTheme(theme);
	}

	/**
	 * 单机打开文件
	 * @param e 
	 */
	@:bind(assets_manager.all_xml, UIEvent.CHANGE)
	public function onFileSelected(e:UIEvent):Void {
		if (assets_manager.all_xml.selectedItem == null)
			return;
		this.editer.addEidtView(assets_manager.all_xml.selectedItem.source.path);
	}

	/**
	 * 双击打开，将自动取消预览模式
	 * @param e 
	 */
	@:bind(assets_manager.all_xml, MouseEvent.DBL_CLICK)
	public function onDBLClickFileSelected(e:UIEvent):Void {
		this.editer.addEidtView(assets_manager.all_xml.selectedItem.source.path, false);
	}

	public function perview(iframe:EditFileView):Void {
		if (iframe == null) {
			return;
		}
		iframe.onLoad(() -> {
			untyped this.iframe.getIFrame()
				.contentWindow.window.perview(projectPath, iframe.url, untyped iframe.frame.getIFrame().contentWindow.window.getCodeValue());
		});
	}
}

typedef TapData = {
	title:String,
	name:String,
	path:String,
	code:String,
	isChange:Bool,
	lock:Bool
}
